<?php

/**
 * Created by PhpStorm.
 * Adminuser: Administrator
 * Date: 2017/3/24
 * Time: 17:37
 */

namespace App\Repositories\Manage;

use Illuminate\Support\Facades\DB;

class UserRepo
{
    protected $userTable = 'manage_user';
    protected $userRoleTable = 'manage_user_role';
    protected $roleTable = 'manage_role';

    /**
     * 获取用户列表
     */
    public function getUserList()
    {

        return DB::table('manage_user')
            ->leftJoin('manage_user_role', 'manage_user.uid', '=', 'manage_user_role.user_id')
            ->leftJoin('manage_role', 'manage_user_role.role_id', '=', 'manage_role.id')
            ->select('manage_user.uid', 'manage_user.name', 'manage_role.name as role_name')
            ->get();
    }

    /**
     * 获取单个用户数据
     * @$where    string
     * $whereArr  array
     */
    public function getUser($where, $whereArr)
    {
        return DB::table($this->userTable)->whereRaw($where, $whereArr)->first();
    }

    /**
     * 获取全部角色
     */
    public function getRoleData()
    {
        return DB::table($this->roleTable)->orderBy('sort', 'desc')->get();
    }

    /**
     * 获取用户对应的角色id
     * @$where    string
     * $whereArr  array
     */
    public function getUserRole($where, $whereArr)
    {
        return DB::table($this->userRoleTable)->select('role_id')->whereRaw($where, $whereArr)->first();
    }


    public function addUserRol($uid, $roleId)
    {
        $len = DB::table($this->userRoleTable)->whereRaw('user_id = ?', [$uid])->count();
        if ($len > 0) {
            $data = [
                'role_id' => $roleId
            ];
            return DB::table($this->userRoleTable)->whereRaw('user_id = ?', [$uid])->update($data);
        } else {
            $data = [
                'user_id' => $uid,
                'role_id' => $roleId
            ];
            return DB::table($this->userRoleTable)->insertGetId($data);
        }


    }

    public function addUser($name,$pass)
    {
        $data=[
           'name' =>$name,
           'pass' =>$pass,
        ];
        return DB::table($this->userTable)->insertGetId($data);
    }

    public function editUser($name,$pass,$uid)
    {
        $data=[
            'name' =>$name,
            'pass' =>$pass,
        ];
        return DB::table($this->userTable)->where('uid',$uid)->update($data);
    }
}